from django.core.mail import send_mail
from django.conf import settings
from django.template import loader,RequestContext
from celery import Celery

#初始化django环境
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailyfresh.settings')
django.setup()
from apps.goods.models import *


app=Celery("celery_tasks.tasks",broker="redis://39.106.207.193:6379/8")

#celery -A celery_tasks.tasks worker --loglevel=info -P eventlet

@app.task
def send_register_active_email(username,to_email,token):
    subject = "天天新鲜邮箱激活"
    message = "<h2 style=\"color:\'red\'\">欢迎%s,请点击以下邮箱激活账号:</h2><a href='http:127.0.0.1:8001/user/active/%s'>http:127.0.0.1:8001/user/active/%s</a>" % (
    username, token, token)
    from_email = '天天生鲜<1741750591@qq.com>'
    recipient_list = [to_email]
    send_mail(subject, "", from_email, recipient_list, html_message=message)

@app.task
def generate_static_index_html():
    """生成首页静态页面"""
    # 获取首页商品分类
    types = GoodsType.objects.all()
    goods_type = IndexTypeGoodsBanner.objects.all()

    # 获取首页banner轮播图
    banners = IndexGoodsBanner.objects.all().order_by("index")

    # 获取首页活动信息
    promotion = IndexPromotionBanner.objects.all().order_by("index")

    # 获取分类详情
    for type in types:
        title_goods = goods_type.filter(type=type, display_type=0)
        image_goods = goods_type.filter(type=type, display_type=1)
        type.title_goods = title_goods
        type.image_goods = image_goods

    # 获取购物车数目
    cart_num = 0

    content = {
        "types": types,
        "banners": banners,
        "promotion": promotion,
        "cart_num": cart_num
    }

    template=loader.get_template("static_index")
    html=template.render(content)
    print(html)
    save_path=os.path.join(settings.BASE_DIR,"templates/static_index.html")
    with open(save_path,"w") as f:
        f.write(html)




